package com.ruoyi.crm.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.vo.ContractVo;
import com.ruoyi.crm.domain.vo.GiveBackVo;
import com.ruoyi.crm.mapper.*;
import com.ruoyi.crm.modules.mq.CrmMqProducer;
import com.ruoyi.crm.service.IAssignRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商机Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-09
 */
@Service
public class BusinessServiceImpl implements IBusinessService
{
    @Resource
    private BusinessMapper businessMapper;

    /**
     * 查询商机
     *
     * @param id 商机主键
     * @return 商机
     */
    @Override
    public Business selectBusinessById(Long id)
    {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询商机列表
     *
     * @param business 商机
     * @return 商机
     */
    @Override
    public List<Business> selectBusinessList(Business business)
    {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business)
    {
        business.setCreateTime(DateUtils.getNowDate());
        return businessMapper.insertBusiness(business);
    }

    /**
     * 修改商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business)
    {

        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(DateUtils.getNowDate());

        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机
     *
     * @param ids 需要删除的商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids)
    {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机信息
     *
     * @param id 商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id)
    {
        return businessMapper.deleteBusinessById(id);
    }


    /**
     *踢回公海
     */
    @Autowired
    private IAssignRecordService assignRecordService;

    @Override
    public int giveBack(Long id) {
        AssignRecord assignRecord = new AssignRecord();
        assignRecord.setId(id);
        assignRecord.setLatest("0");
        assignRecord.setType(AssignRecord.Type.BUSINESS.getValue());
        assignRecordService.updateAssignRecord(assignRecord);

        Business business = businessMapper.selectBusinessById(id);
        business.setStatus(Clue.Status.FALSE.getValue());//状态设置为--->踢回公海
        return businessMapper.updateBusiness(business);
    }



    /**
     *捞取商机
     */
    @Override
    public int reset1(Long id) {
        AssignRecord assignRecord = new AssignRecord();
        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setAssignId(id);
        assignRecord.setUserId(SecurityUtils.getUserId());
        assignRecord.setUserName(SecurityUtils.getUsername());
        return assignRecordService.insertAssignRecord(assignRecord);
    }


    /**
     *捞取商机  批量捞取商机
     */
    @Override
    public int resetList(List<GiveBackVo> giveBackVo) {
        int count = 0;
        for (GiveBackVo backVo : giveBackVo) {
            count += this.reset(backVo);
        }
        return count;
    }

    @Override
    public int reset(GiveBackVo giveBackVo) {
        AssignRecord assignRecord = new AssignRecord();

        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setAssignId(giveBackVo.getId());
        assignRecord.setUserName(SecurityUtils.getUsername());
        assignRecord.setUserId(SecurityUtils.getUserId());

        setUserInfo(assignRecord, SecurityUtils.getUsername());

        return assignRecordService.insertAssignRecord(assignRecord);
    }


    public void setUserInfo(AssignRecord assignRecord, String owner) {
        Map<String, Object> userInfo = getUserInfo(owner);

        assignRecord.setUserId((Long) userInfo.get("user_id"));
        assignRecord.setDeptId((Long) userInfo.get("dept_id"));
        assignRecord.setUserName(owner);
    }

@Resource
private ClueMapper clueMapper;
    public Map<String, Object> getUserInfo(String owner) {
        final String key = "crm:clue:userInfo" + owner;
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        Map<String, Object> map = redisCache.getCacheMap(key);
        if (map.isEmpty()) {
            map = clueMapper.selectUserInfo(owner);
            redisCache.setCacheMap(key, map);
            redisCache.expire(key, 5, TimeUnit.MINUTES);
        }
        return map;
    }


    /**
     *转客户
     */
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CrmMqProducer crmMqProducer;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private ActivityMapper activityMapper;

    @Override
    @Transactional
    public int transform2Customer(ContractVo contractVo) {
        //更新商机状态
        Business business = businessMapper.selectBusinessById(contractVo.getId());
        if (business.getCourseId() == null) {
            throw new RuntimeException("商机里面没有选择课程，无法转换客户合同");
        }
        if (contractMapper.selectContractByNo(contractVo.getContractNo()) != null) {
            throw new RuntimeException("合同编号已经存在，无法转换客户合同");
        }
        business.setStatus(Clue.Status.TO_CUSTOMER.getValue());
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(new Date());
        businessMapper.updateBusiness(business);


        //插入合同
        Contract contract = new Contract();

        BeanUtils.copyProperties(business, contract);

        contract.setBusinessId(contractVo.getId());
        contract.setContractNo(contractVo.getContractNo());
        contract.setFileName(contractVo.getFileName());
        contract.setPhone(contractVo.getPhone());
        contract.setEmail(contractVo.getEmail());

        String businesskey = Seq.getId();
        contract.setId(businesskey);
        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setDeptId(SecurityUtils.getDeptId());
        contract.setStatus("4");
        //根据活动计算优惠后的金额
        setContractOrder(contract);
        contractMapper.insertContract(contract);
        //通过邮件和
        crmMqProducer.produceContractCreatedMessage(contract);
        return 1;
    }


    private void setContractOrder(Contract contract) {
        Course course = courseMapper.selectCourseById(contract.getCourseId());
        contract.setCourseName(course.getName());
        Activity activity = null;
        if (contract.getActivityId() != null) {
            activity = activityMapper.selectActivityById(contract.getActivityId());
        }
        if (activity == null) {
            contract.setContractOrder(course.getPrice());
        } else {
            if ("1".equals(activity.getType())) {
                contract.setDiscountType("课程折扣");
                contract.setContractOrder(activity.getDiscount() / 10.0 * course.getPrice());
                //如果不改变类里面的属性就直接Double.value
//                contract.setContractOrder(Double.valueOf(activity.getDiscount() / 10.0 * course.getPrice()));
            } else {
                contract.setDiscountType("代金券");
                contract.setContractOrder(course.getPrice() - activity.getVouchers());
            }
            contract.setCoursePrice(course.getPrice());
        }
    }

}
